﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace net6ApiUploadAndDownload.Controllers
{
    [Route("api/[controller]/action")]
    [ApiController]
    public class FileController : ControllerBase
    {
        private readonly IFileService fileService;

        public FileController(IFileService fileService)
        {
            this.fileService = fileService;
        }
        /// <summary>
        ///  上传功能
        /// </summary>
        /// <param name="formFiles">上传的文件</param>
        /// <param name="subDirectory">把文件上传到的具体的路径</param>
        /// <returns></returns>
        [HttpPost(nameof(Upload))]
        //[RequestFormLimits(ValueLengthLimit = int.MaxValue, MultipartBodyLengthLimit = long.MaxValue)]
        [RequestSizeLimit(long.MaxValue)]        //默认是上传30M，加上之后可，可以增大
        public IActionResult Upload([Required] List<IFormFile> formFiles, [Required] string subDirectory)
        {
            try
            {
                if (formFiles.Count > 0)
                {

                }
                fileService.UploadFile(formFiles, subDirectory);

                return Ok(new { formFiles.Count, Size = fileService.SizeConverter(formFiles.Sum(f => f.Length)) });
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        /// <summary>
        /// 下载功能
        /// </summary>
        /// <param name="subDirectory">下载文件夹的路径或者下载的文件路径</param>
        /// <returns></returns>
        [HttpGet(nameof(Download))]
        public IActionResult Download([Required] string subDirectory)
        {
            try
            {
                var (fileType, archiveData, archiveName) = fileService.DownloadFiles(subDirectory);

                return File(archiveData, fileType, archiveName);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

    }
}
